package org.adorsys.aderp.jpa.impl;

import org.adorsys.aderp.jpa.api.audit.AbstractAuditRecord;
import org.adorsys.aderp.jpa.api.audit.AuditRecordBuilder;
import org.adorsys.aderp.jpa.api.audit.ModifMode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.BeanFactory;

/**
 * Holds information associated with audit record.
 * 
 * @author francis
 *
 */
public class AuditRecordInfo<AR extends AbstractAuditRecord> extends RepositoryResolver {

	private final Class<AR> auditRecordClass;
	
	/**
	 * used to create the audit record.
	 */
	private final AuditRecordBuilder auditRecordBuilder;

	public AuditRecordInfo(
			Class<AR> auditRecordClass,
			AuditRecordBuilder auditRecordBuilder,
			BeanFactory beanFactory) {
		super(beanFactory, auditRecordClass);
		this.auditRecordClass = auditRecordClass;
		this.auditRecordBuilder = auditRecordBuilder;
	}
	

	@SuppressWarnings("unchecked")
	public void createAuditRecord(String businessKey, Object entity, 
			ModifMode mode, String envData) {
		AR auditRecord = auditRecordBuilder.buildRecord(businessKey, entity, auditRecordClass);
		if(StringUtils.isNotBlank(envData))auditRecord.setEnvData(envData);
		auditRecord.setModifMode(mode);
		if(getRepository()==null) return;
		getRepository().save(auditRecord);
	}
}
